﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvidenceLib.System;
using EvidenceService.Core;
using EvidenceService.System;
using EvidenceWeb.Util;
using NHibernate;

namespace EvidenceWeb.Controllers
{
    public class SystemController : Controller
    {
        //
        // GET: /System/

        public ActionResult Index()
        {
            return View();
        }

        #region 组织机构

        public ActionResult LoadOrganizationList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                OrganizationService svr = new OrganizationService(session);

                IList<Organization> es = svr.LoadByHQL(string.Format("from Organization where  Name like {0} order by OrderNo", "'青羊区%'"));

                string json = JsonSerializerUtil.EntityToJson(es);

                return Json(new { IsSuccess = true, Data = json });
            }
        }

        public ActionResult LoadOrganizationListByStorage()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                OrganizationService svr = new OrganizationService(session);

                IList<Organization> es = svr.LoadByHQL(string.Format("from Organization as o where exists (from Storage as s  where s.ManageDept.Id=o.Id) and  Name like {0} order by OrderNo", "'青羊区%'"));

                string json = JsonSerializerUtil.EntityToJson(es);

                return Json(new { IsSuccess = true, Data = json });
            }
        }

        #endregion

        public ActionResult LoadUserListByDeptId()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    int deptId = 0;
                    int.TryParse(Request["deptId"], out deptId);

                    UserService svr = new UserService(session);

                    IList<User> users = svr.LoadByHQL("from User as u where u.Department.Id =" + deptId + " order by u.Name");

                    string json = JsonSerializerUtil.EntityToJson(users);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }


        #region 系统设置

        public ActionResult SystemSettingView()
        {
            return View();
        }

        public ActionResult LoadSystemParameterList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                SystemParameterService svr = new SystemParameterService(session);

                IList<SystemParameter> es = svr.LoadByHQL("from SystemParameter");

                string json = JsonSerializerUtil.EntityToJson(es);

                return Json(new { IsSuccess = true, Data = json });
            }
        }

        public ActionResult SaveSystemParameterList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                ITransaction tx = session.BeginTransaction();
                try
                {
                    string json = Request["SystemParameters"];


                    IList<SystemParameter> sps = JsonSerializerUtil.JsonToEntities<SystemParameter>(json);

                    SystemParameterService svr = new SystemParameterService(session);

                    foreach (var sp in sps)
                    {
                        svr.SaveOrUpdate(sp);
                    }
                    tx.Commit();
                    return Json(new { IsSuccess = true });
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        public ActionResult LoadSystemParameter()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    string fkey = Request["systemParameterKey"];

                    SystemParameterService svr = new SystemParameterService(session);

                    SystemParameter sp = svr.LoadByHQL(string.Format("from SystemParameter where FKey='{0}'", fkey)).FirstOrDefault();

                    string json = JsonSerializerUtil.EntityToJson(sp);

                    return Json(new { IsSuccess = true, Data = json });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        #endregion


        #region 角色管理

        public ActionResult RoleManageView()
        {
            return View();
        }

        public ActionResult RoleListView()
        {
            return View();
        }
        /// <summary>
        /// 获取所有警员的列表
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadPoliceList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                IEnumerable<object> ls = new List<object>();
                UserService svr = new UserService(session);
                try
                {
                    string wheresql = "";

                    int pageIndex = 0;
                    int.TryParse(Request["page"], out pageIndex);

                    int pageSize = 0;
                    int.TryParse(Request["rows"], out pageSize);

                    string userCode = Request["PoliceCode"];
                    string userName = Request["PoliceName"];
                    string userStation = Request["PoliceStation"];
                    if (!string.IsNullOrEmpty(userCode))
                    {
                        wheresql += string.Format(" and u.Number like '%{0}%' ", userCode);
                    }
                    if (!string.IsNullOrEmpty(userName))
                    {
                        wheresql += string.Format(" and u.Name like '%{0}%' ", userName);
                    }
                    if (!string.IsNullOrEmpty(userStation))
                    {
                        wheresql += string.Format(" and u.Department.Name like '%{0}%' ", userStation);
                    }
                    string baseHql = "from User as u   where u.IsUsed != 0 or u.IsUsed is NULL ";
                    string hql = null;
                    string totalHql = null;

                    totalHql = "select count(u.Id) " + baseHql + wheresql;
                    hql = "select u " + baseHql + wheresql + " order by u.Department.Id";
                    Tuple<IList<User>, int> result = svr.LoadListByHQLWithPaging(hql, totalHql, pageSize, pageIndex);

                    ls = (from b in result.Item1
                          select new
                          {
                              Id = b.Id,
                              Name = b.Name,
                              Code = b.Number,
                              OrganizationName = b.Department == null ? "" : b.Department.Name.EndsWith("青羊区分局") ? b.Department.Name : b.Department.Name.Replace("青羊区分局", ""),
                              OrganizationId = b.Department == null ? 0 : b.Department.Id,
                              Sex = b.Sex,
                              IDCard = b.IDCard
                          });
                    return Json(new { total = result.Item2, rows = ls });
                }
                catch (Exception ex)
                {
                    return Json(new { total = 0, rows = ls });
                }

            }
        }

        /// <summary>
        /// 获取所有角色列表，已有的选中
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadRoleList()
        {
            IEnumerable<object> ls = new List<object>();
            try
            {
                string pId = Request["policeId"];
                int policeId = int.Parse(pId);
                using (ISession session = HbmSessionFactory.GetSession())
                {
                    RoleService svr = new RoleService(session);

                    IList<Role> rolelist = svr.LoadByHQL(" from Role ");
                    ls = (from r in rolelist
                          select new
                          {
                              Id = r.Id,
                              Name = r.Name,
                              Description = r.Description,
                              CheckedId = GetCheckedRolesByPId(policeId)
                          });
                    return Json(new { total = rolelist.Count, rows = ls });
                }
            }
            catch (Exception ex)
            {
                return Json(new { total = 0, rows = ls });
            }
        }




        public string GetCheckedRolesByPId(int pId)
        {
            if (pId > 0)
            {
                using (ISession session = HbmSessionFactory.GetSession())
                {
                    PoliceRoleService svr = new PoliceRoleService(session);
                    try
                    {
                        string idStr = "";
                        IList<PoliceRole> roleList = new List<PoliceRole>();
                        roleList = svr.LoadByHQL(string.Format(" from PoliceRole p where p.PoliceManId={0} ", pId));

                        for (int i = 0; i < roleList.Count; i++)
                        {
                            idStr += roleList[i].RoleId + ",";
                        }
                        if (idStr.Length > 0)
                        {
                            idStr = idStr.Substring(0, idStr.Length - 1);
                        }
                        return idStr;
                    }
                    catch (Exception ex)
                    {
                        return "";
                    }
                }
            }
            else
            {
                return "";
            }
        }

        public ActionResult SavePoliceRole()
        {
            int policeId = 0;
            int.TryParse(Request["policeId"], out policeId);
            if (policeId > 0)
            {
                using (ISession session = HbmSessionFactory.GetSession())
                {
                    PoliceRoleService svr = new PoliceRoleService(session);
                    try
                    {
                        string roleId = Request["Roles"];
                        List<string> IdList = null;
                        if (string.IsNullOrEmpty(roleId))
                        {
                            IdList = new List<string>();
                        }
                        else
                        {
                            IdList = roleId.Split(',').ToList();
                        }
                        svr.DeletebyHQL(string.Format("delete from  PoliceRole where PoliceManId ={0}", policeId));
                        for (int i = 0; i < IdList.Count; i++)
                        {
                            PoliceRole pRole = new PoliceRole();
                            int ids = 0;
                            pRole.PoliceManId = policeId;
                            int.TryParse(IdList[i], out ids);
                            if (ids > 0)
                            {
                                pRole.RoleId = ids;
                                svr.SaveOrUpdate(pRole);
                            }
                        }
                        return Json(new { IsSuccess = true });
                    }
                    catch (Exception ex)
                    {
                        return Json(new { IsSuccess = false, Message = ex.Message });
                    }
                }
            }
            else
            {
                return Json(new { IsSuccess = false, Message = " 传入后台Id出错！" });
            }
        }

        public ActionResult CheckAuthority()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                User user = this.Session["User"] as User;

                if (user == null)
                {
                    return Json(new { IsSuccess = false, Data = "操作已超时,请重新登录!" });
                }

                if (user.Name.ToLower() == "admin")
                {
                    return Json(new { IsSuccess = true });
                }

                string roleKey = Request["roleKey"];

                string sql = "select count(*) from EV_PoliceRole as pr inner join Ev_Role as r on pr.RoleId=r.Id  where pr.PoliceManId=" + user.Id + " and (r.FKey='admin' or r.FKey ='" + roleKey + "')";
                int count = session.CreateSQLQuery(sql).UniqueResult<int>();

                return Json(new { IsSuccess = count > 0 ? true : false });
            }
        }

        #endregion
    }
}
